<?php
//>> 兑换金币

if(!defined('IN_DISCUZ')) exit('Access Denied!');

function saveLog($file, $str) {
    file_put_contents($file, $str.PHP_EOL, FILE_APPEND);
}

function costCredit($cost) {
    global $_G;
    if(!updatemembercount($_G['uid'], array($_G['setting']['creditstrans'] => -$cost), false, '', $_G['uid'])) {
        updatecreditbyaction('buy_wow_gold');
        return true;
    }
    return false;
}

function httpGet($url, &$err) {
    //初始化
    $ch = curl_init();

    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    if (!$output) {
        $err = curl_error($ch);
    }

    //释放curl句柄
    curl_close($ch);

    return $output;
}

// 插件配置
$plugin_conf = $_G['cache']['plugin']['mangos'];

// 大芒果接口
$mangos_smapi = $plugin_conf['mangos_smapi'];
$mangos_s2g = $plugin_conf['mangos_s2g'];
$mangos_log = $plugin_conf['mangos_log'];

// 获取用户金钱数量
$credits = getuserprofile('extcredits'.$_G['setting']['creditstrans']);

if ($_REQUEST['buy']) {
    $server_name = $_REQUEST['server'];
    $chara_name = $_REQUEST['chara'];
    $score = intval($_REQUEST['score']);

    $gold = intval($score / $mangos_s2g);

    $log = array(
        'server' => $server_name,
        'chara' => $chara_name,
        'score' => $score,
        'date' => time()
    );

    if (!is_numeric($score) || $score <= 0) {
        $log['err'] = '参数错误';
        $error = '参数错误';
    } else if($credits <= 0 || $credits < $score){
        $log['err'] = '积分不足';
        $error = '积分不足';
    } else {
        if (!costCredit($score)) {
            $error = '扣除积分失败';
            $log['err'] = '扣除积分失败';
        } else {
            $url = sprintf('%s&sname=%s&name=%s&gold=%d', $mangos_smapi, $server_name, $chara_name, $gold);
            // 发送邮件
            $httpErr = '';
            $res = httpGet($url, $httpErr);
            if (!$res) {
                $log['err'] = 'HTTP 请求失败';
                $error = $httpErr;
            } else {
                $res = json_decode($res, true);

                if ($res['code'] != 0) {
                    $error = $res['desc'];
                    $log['err'] = $res['desc'];
                } else {
                    $msg = '<h1>购买成功</h1>';
                    $log['err'] = '购买成功';
                }
            }
        }
    }

    saveLog($mangos_log, json_encode($log));
}

if ($error) {
    $error = $error . ', 请联系GM！';
}